/**
 * @description home路由的控制器
 * @author 印明帝
 */
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { getAtListFailInfo,getBlogFailInfo } = require('../model/errorInfo')
const { getBlogs } = require('../service/blog')
const { getFollowersBlogList } = require('../service/blog')
const { getUsersByFollower,getFollowersByUser } = require('../service/userRelation')


/**
  * 获取首页的数据
  * @method getHome
  * @param {Object} ctx 
  */
async function getHome(ctx) {
  // 获取当前登录的用户id
  let { id: userId } = ctx.session.userInfo
  let blogData = {},userData = {},fansData = {},followerData = {}
  // 博客数据
  blogData = await getFollowersBlogList(userId)
  // isMe 
  userData = ctx.session.userInfo
  userData.isMe = true
  // 获取粉丝列表
  fansData = await getUsersByFollower(userId)
  // userData中amIFollow判断我是不是他的粉丝
  userData.amIFollow = fansData.userList.some((user) => user.userId === userId)
  // 关注人的列表
  followerData = await getFollowersByUser(userId)

  let result = {
    blogData,
    userData,
    fansData,
    followerData
  }
  if(result) {
    return new SuccessModel(result)
  }
  return new ErrorModel(getBlogFailInfo)
} 
/**
 * 获取首页的博客列表
 * @method getHomeBlogList
 * @param {Object} ctx
 */
async function getHomeBlogList(ctx) {
  let {id: userId} = ctx.session.userInfo
  let {index} = ctx.query
  let result = await getFollowersBlogList(userId,index)
  if(result) {
    return new SuccessModel(result)
  }
  return new ErrorModel(getBlogFailInfo)
}

/**
 * 获取@ 列表人
 * @method getHomeBlogList
 * @param {Object} ctx
 */
async function getAtList(ctx) {
  // 获取当前登录的用户id
  let { id: userId } = ctx.session.userInfo
  // 关注人的列表
  let result = await getFollowersByUser(userId)
  // 格式化
  let atList = result.userList.map((user) => {
    return {
      key: user.id,
      value: `${user.nickName} - ${user.id}`
    }
  })
  if(result) {
    return new SuccessModel(atList)
  }
  return new ErrorModel(getAtListFailInfo)
}

module.exports = {
  getHome,
  getHomeBlogList,
  getAtList
}